<template>
  <div class="contianer">
    <edit-page-new
      @goBackPage="goBackPage"
      :rightBtnArr="rightBtnArr"
      :showTopTitle="false"
      :showBackBtn="true"
    >
      <dividerTitle :title="'用户信息'"></dividerTitle>
      <div class="content">
        <div class="form">
          <edit-form
            :formConfig="formConfig"
            ref="editForm"
            :formData="userFormData"
          ></edit-form>
          <div class="param">
            <label class="desc">岗位</label>
            <div class="list">
              <span
                class="item"
                v-for="(item, index) in postUserVoList"
                :key="index"
              >
                {{ item }}
              </span>
              
                <el-tooltip
                  effect="dark"
                  content="角色未授权"
                  :disabled="btnDisabled"
                  :placement="'top'"
                >
                  <span class="itemBtn">
                    <el-button
                      style="margin:12px:20px"
                    
                      icon="el-icon-plus"
                      :disabled="!btnDisabled"
                      @click="addPosting"
                      >新建</el-button
                    >
                  </span>
                </el-tooltip>
              
            </div>
          </div>
        </div>
        <div class="picture">
          <el-upload
            ref="upload"
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :on-change="handleChange"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :auto-upload="false"
            accept=".jpg,.png"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-button type="danger" size="mini" @click="deletePhoto"
            >删除头像</el-button
          >
        </div>
      </div>
    </edit-page-new>
    <dialogPublic
      title="选择组织"
      :show.sync="show"
      @doSubmit="doSubmit"
      @doClose="() => (show = false)"
    >
      <div style="height: 300px">
        <tableList ref="klTable" v-bind="tableConfig"></tableList>
      </div>
    </dialogPublic>
    <dialogPublic
      :title="'信息选择'"
      :show.sync="showMember"
      width="80%"
      @doSubmit="addSeleteMember"
      @doClose="() => (showMember = false)"
      appendTobody
    >
      <postSelect ref="postSelect" v-if="showMember"></postSelect>
    </dialogPublic>
  </div>
</template>

<script>
import {
  getUserDataByAccount,
  addOrEditUser,
  deleteOnceUser,
} from "@/api/systemManagement/userManagement.js";
import { queryUserList } from "@/api/common";
import { postUserAdd } from "@/api/systemManagement/postConfig.js";
import tableList from "@/components/memberSelect/tableList.vue";
import postSelect from "./postSelect.vue";
export default {
  components: { tableList, postSelect },
  props: {
    editFormData: {
      type: Object,
      default: function () {
        return {};
      },
    },
    orgId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      show: false,
      selectOrgName: null,
      showMember: false,
      rightBtnArr: [
        {
          icon: "icon-a-wanchengbaocun",
          text: "保存",
          hide: false,
          methods: () => {
            this.save();
          },
        },
        {
          icon: "icon-shanchu",
          text: "删除",
          hide: false,
          methods: () => {
            this.$confirm("确定要删除这条数据吗", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                this.deleteOnce();
              })
              .catch((e) => {});
          },
        },
      ],
      formConfig: {
        labelWidth: "100px",
        itemArr: [
          {
            span: 12,
            label: "用户名",
            prop: "name",
            type: "text",
            disabled: false,
            required: true,
          },
          {
            span: 12,
            label: "账号",
            prop: "account",
            type: "text",
            disabled: true,
            required: true,
          },
          {
            span: 12,
            rows: 2,
            label: "组织",
            prop: "orgNames",
            idsStr: "orgIds",
            propArr: "orgIdArr",
            type: "dept",
            option: [],
            multiple: true,
            required: true,
            methods: (data, formData) => {
              let change = true;
              let orgList = data.map((item) => {
                let obj = {
                  account: this.userFormData.account,
                  orgId: item.id,
                };
                if (formData.defaultOrgId && item.id == formData.defaultOrgId) {
                  obj.defaultFlag = 1;
                  change = false;
                } else {
                  obj.defaultFlag = 0;
                }
                return obj;
              });
              this.$refs.editForm.setFormItem("orgVoList", data);
              this.$refs.editForm.setFormItem("appUserOrgPos", orgList);
              change && this.$refs.editForm.setFormItem("defaultOrgId", null);
              let options = data.map((item) => {
                let obj = {
                  label: `${item.levelPathName}/${item.name}`,
                  value: item.id,
                };
                return obj;
              });
              this.$set(this.formConfig.itemArr[4], "selectOption", options);
            },
          },
          {
            span: 12,
            label: "手机号",
            prop: "phone",
            type: "text",
            required: true,
            rules: {
              message: "请输入正确的手机号码",
              trigger: "blur",
              validator: (rule, value, callback) => {
                var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
                if (!myreg.test(value)) {
                  return callback(new Error("请输入正确的11位手机号码"));
                } else {
                  callback();
                }
              },
            },
          },
          {
            span: 12,
            label: "默认组织",
            prop: "defaultOrgId",
            type: "select",
            methods: (val, formData) => {
              let appUserOrgPos = formData.orgVoList.map((item) => {
                let obj = {
                  account: this.userFormData.account,
                  orgId: item.id,
                };
                obj.defaultFlag = item.id == val.value ? 1 : 0;
                return obj;
              });
              this.$refs.editForm.setFormItem("appUserOrgPos", appUserOrgPos);
            },
          },
          {
            span: 12,
            label: "默认租户",
            prop: "defaultAppId",
            type: "select",
            methods: (val, formData) => {
              //formData.defaultAppId = val.value;
            },
          },

          {
            label: "性别",
            prop: "sex",
            type: "radio",
            span: 12,
            radioOption: [
              { label: "男", value: "1" },
              { label: "女", value: "0" },
            ],
            required: true,
          },
          {
            span: 12,
            label: "邮箱地址",
            prop: "email",
            type: "text",
            required: false,
            rules: {
              message: "请输入正确的邮箱格式",
              trigger: "blur",
              validator: (rule, value, callback) => {
                const mailReg =
                  /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
                if (!mailReg.test(value) && value) {
                  return callback(new Error("请输入正确的邮箱格式"));
                } else {
                  callback();
                }
              },
            },
          },
          {
            span: 12,
            label: "密码有效期",
            prop: "expiringTime",
            type: "text",
            disabled: true,
            required: false,
          },
          {
            span: 12,
            label: "密码强度",
            prop: "strength",
            type: "text",
            disabled: true,
            required: false,
          },
        ],
      },
      userFormData: {},
      postUserVoList: [],
      imageUrl: null,
      photoFile: null,
      delPhotoId: null,
      tableConfig: {
        radioShow: true,
        showAllSearch: true,
        showIndex: false,
        selectionShow: false,
        showFilterBtn: false,
        showCustomBtn: false,
        rowKey: "idAndOrgId",
        searchObj: {
          searchMethod: (params, sortStr) => {
            this.getTableData(params, sortStr);
          },
          searchArr: [],
          queryData: {},
        },
        tableMethods: {
          rowClick: (row) => {
            this.$refs.klTable.radioSelect(row);
          },
        },
        actionList: [],
        column: [
          {
            label: "所属组织",
            prop: "orgName",
          },
          {
            label: "用户名",
            prop: "name",
          },
        ],
        tableData: [],
        paginationObj: {
          pageSizes: [15, 30, 50, 100],
        },
        totalNumber: 0,
        showPagetion: false,
        pageSmall: true,
      },
      btnDisabled: this.$store.getters.isBtnAuth("addPending"),
    };
  },
  created() {
    if (this.editFormData.photo != "") {
      this.getImgUrl(this.editFormData.photo);
    }
  },
  mounted() {
    this.getUserInfo(this.editFormData.account);
  },
  watch: {
    editFormData: {
      handler(val) {
        if (val.photo != "") {
          this.getImgUrl(val.photo);
        }
        this.getUserInfo(val.account);
      },
      deep: true,
    },
    // showTable: {
    //   handler(val) {
    //     if (val) {
    //       this.getUserInfo(this.editFormData.account);
    //     }
    //   },
    // },
  },
  methods: {
    //获取用户信息
    getUserInfo(val) {
      getUserDataByAccount({ account: val }).then((res) => {
        let data = res.data;
        let orgOption = data.orgVoList.map((item) => {
          const obj = {
            label: `${item.levelPathName}/${item.name}`,
            value: item.id,
          };
          return obj;
        });
        this.$set(this.formConfig.itemArr[4], "selectOption", orgOption);
        let defaultOrg = data.orgVoList.filter((item) => item.defaultFlag == 1);
        data.defaultOrgId = defaultOrg.length != 0 ? defaultOrg[0].id : "";
        let appOption = data.appSimpleBeanList
          ? data.appSimpleBeanList.map((item) => {
              const obj = {
                label: item.appName,
                value: item.appMark,
              };
              return obj;
            })
          : [];
        this.$set(this.formConfig.itemArr[5], "selectOption", appOption);
        data.orgIds = data.orgVoList.map((item) => item.id).join(",");
        data.orgNames = data.orgVoList.map((item) => item.name).join(",");
        this.userFormData = data;
        // let orgIdArr = data.orgVoList.map((item) => item.id);
        // let option = data.orgVoList.map((item) => {
        //   let obj = {
        //     label: item.name,
        //     value: item.id,
        //     id: item.id,
        //     name: item.name,
        //     isOutOrg: item.outOrg,
        //   };
        //   return obj;
        // });
        // setTimeout(() => {
        //   this.$refs.editForm.setItemOption("orgNames", option);
        //   this.$refs.editForm.setFormItem("orgIdArr", orgIdArr);
        // }, 0);
        this.postUserVoList = data.postUserVoList
          ? data.postUserVoList.map((item) => {
              return item.postName;
            })
          : [];
      });
    },
    //头像获取成功
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.photoFile = file;
    },
    //上传图片前的格式判断
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isLt2M) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //头像改变
    handleChange(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt10M = file.size / 1024 / 1024 <= 10;
      if (!isJPG) {
        this.imageUrl = URL.createObjectURL(file.raw);
        this.photoFile = file;
      } else {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt10M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
      }
    },
    //通过photo获取图片地址
    async getImgUrl(id) {
      if (id) {
        this.imageUrl = await this.$utils.echoImg(id);
      }
    },
    //删除头像
    deletePhoto() {
      this.imageUrl = null;
      this.photoFile = null;
    },
    //保存用户信息
    async save() {
      try {
        let data = await this.$refs.editForm.getFormData();
        delete data.orgVoList;
        delete data.appSimpleBeanList;
        if (!this.imageUrl) {
          this.delPhotoId = data.photo;
          data.photo = null;
        }
        const params = {
          delPhotoId: this.delPhotoId,
        };
        const formData = new FormData();
        formData.append("staffBeanStr", JSON.stringify(data));
        let res;
        if (this.photoFile) {
          formData.append("photo", this.photoFile.raw);
          res = await addOrEditUser(params, formData);
        } else {
          res = await addOrEditUser(params, formData);
        }
        this.$message.success(res.description);
        this.$emit("getNewest");
      } catch (error) {
        this.$message.error(error);
      }
    },
    //删除单条数据
    deleteOnce() {
      let params = {
        id: this.editFormData.id,
        orgId: this.orgId,
      };
      deleteOnceUser(params).then(
        (res) => {
          if (res.code === 200) {
            this.$message.success(res.description);
            this.$emit("getNewest");
          }
        },
        (error) => {
          this.$message.error(error);
        }
      );
    },
    //返回
    goBackPage() {
      this.$emit("goBackPage");
    },
    //新增岗位
    addPosting() {
      this.show = true;
      this.getTableData({ page: 1, pageSize: 100 }, []);
    },
    //获取表格数据
    getTableData(params, sortStr) {
      let queryData = Object.assign({}, params);
      queryData.permission = true;
      queryData.account = this.editFormData.account;
      //queryData.name = this.editFormData.account;
      if (sortStr.length > 0) {
        queryData.orders = sortStr;
      }
      queryData.orgId = this.orgCode;
      queryUserList(queryData).then((res) => {
        res.data.forEach((item) => {
          item.idAndOrgId = item.id + item.orgId;
        });
        this.$set(this.tableConfig, "tableData", res.data);
        this.$set(this.tableConfig, "totalNumber", res.total);
      });
    },
    doSubmit() {
      let selectData = this.$refs.klTable.getRadioData();
      if (selectData) {
        this.selectOrg = selectData;
        this.show = false;
        this.showMember = true;
      } else {
        this.$message.warning("请选择组织");
      }
    },
    addSeleteMember() {
      let data = this.$refs.postSelect.getSelectData();
      let params = data.map((item) => {
        let obj = {
          postId: item.id,
          userAccount: this.editFormData.account,
          userOrg: this.selectOrg.orgId,
        };
        return obj;
      });
      postUserAdd(params).then((res) => {
        if (res.code == 200) {
          this.showMember = false;
          this.$message.success("新增成功");
          this.getUserInfo(this.editFormData.account);
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.contianer {
  width: 100%;
  height: 100%;
  background-color: white;
  .content {
    display: flex;
    margin-top: 30px;
    .form {
      flex: 4;
      padding-right: 30px;
    }
    .picture {
      flex: 1;
      /deep/ .avatar-uploader {
        .el-upload {
          border: 1px dashed rgb(34, 33, 33);
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
          .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
          }
          .avatar {
            width: 178px;
            height: 178px;
            display: block;
          }
        }
        .el-upload:hover {
          border-color: #409eff;
        }
      }
    }
  }
  .param {
    margin: 10px 10px;
    display: flex;
    .desc {
      height: 40px;
      line-height: 40px;
      font-size: 14px;
      margin: 0 15px 0 50px;
    }
    .item {
      padding: 5px 12px;
      margin: 10px 0;
      text-align: center;
      height: 32px;
      line-height: 32px;
      background-color: #f4f4f4;
      border-radius: 4px;
      margin-right: 15px;
    }
    .itemBtn {
      margin: 10px 0;
      text-align: center;
      height: 42px;
      line-height: 42px;
      border-radius: 4px;
      margin-right: 15px;
    }
    .list {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
    }
  }
}
</style>
